import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pdf/model/ConvertTypes.dart';

import '../../api/ApiUtils.dart';
import '../../api/request/ConvertRequest.dart';
import '../../base/MyScaffold.dart';
import '../../config/Constant.dart';
import '../../model/Bus.dart';
import '../../model/Process.dart';
import '../../model/TokenEntity.dart';
import '../../model/Types.dart';
import '../../model/UserEntity.dart';
import '../../res.dart';
import '../../sqflite/CreateTableSqls.dart';
import '../../sqflite/DBUtil.dart';
import '../../utils/EventBus/EventBus.dart';
import '../../utils/Toast/MyTosat.dart';
import '../../utils/Tool/MyTools.dart';
import '../../utils/Tool/SaveFile.dart';
import '../../utils/color/ColorUtils.dart';
import '../../utils/permission/PermissionUtils.dart';
import '../../utils/userbloc/user_bloc.dart';
import '../../widgets/MyLocalImage.dart';
import '../../widgets/TextView.dart';
import '../dialog/TypeDialog.dart';
import '../permissions/Permissions.dart';
import '../subscribe/Subscribe.dart';

class ConvertPDF extends StatefulWidget {
  ConvertPDF({Key? key, required this.type}) : super(key: key);
  Types type;
  @override
  State<ConvertPDF> createState() => _ConvertPDFState();
}

class _ConvertPDFState extends State<ConvertPDF> {
  late File file;
  late DBUtil dbUtil;
  late String ConvertType;
  UserEntity? userEntity;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dbUtil = DBUtil();
    ConvertType = widget.type.types.first;
    userEntity = UserBlocTool.userEntity;
  }

  setType(String type) {
    ConvertType = type;
    setState(() {});
  }

  checkPermission() {
    PermissionUtils.checkReadWritePermission().then((status) {
      if (status) {
        _selectFile(widget.type.name);
      } else {
        Get.to(const Permissions());
      }
    });
  }

  Future<void> _selectFile(String type) async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: getType(widget.type), // 允许选择的文件扩展名
    );

    if (result != null) {
      file = File(result.files.single.path!);
      // 在这里处理文件，例如读取文件内容或显示文件信息
      Get.back();
      Process process = Process(
          name: file.path.split(Platform.pathSeparator).last,
          path: file.path,
          type: type,
          img: widget.type.img,
          label: widget.type.label,
          value: MyTools.getRandom(),
          state: 0);
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.mobile ||
          connectivityResult == ConnectivityResult.wifi) {
        EventBusUtil.fireEvent(Bus(Constant.CONVERT_MSG, process));
      } else {
        MyToast().show("network".tr, icon_tips: false);
      }
      apiShow(
          api: getToken(),
          success: (value) async {
            //EventBusUtil.fireEvent(Bus(Constant.CONVERT_LOGIN_MSG, null));
            TokenEntity token = TokenEntity.fromJson(value.data);

            int id = await setData(process);
            if (widget.type.label == 4) {
              //上传
              apiShow(
                  api: Upload(file.path, token),
                  success: (value) {
                    //分割
                    apiShow(
                        api: Split(
                          file.path,
                          ConvertType.toLowerCase(),
                          true,
                          token,
                        ),
                        success: (value) {
                          //下载
                          apiShow(
                              api: Download(
                                value.data,
                                token,
                              ),
                              success: (value) {
                                print("======图片压缩成功=======");
                                process.state = 1;
                                var type = ConvertType.toLowerCase();
                                List<String> splitString =
                                process.name.split("."); // 以逗号和空格为分隔符拆分字符串
                                String substring = splitString[0];
                                saveFile(value.data, "$substring.zip")
                                    .then((v) {
                                  EventBusUtil.fireEvent(
                                      Bus(Constant.CONVERT_MSG, process));
                                  update(id, 1, path: v);
                                  if (type == "pdf") {
                                    EventBusUtil.fireEvent(
                                        Bus(Constant.ADD_FILE_MSG, File(v)));
                                  }
                                });
                              });
                        });
                  });
              // apiShow(
              //     api: Download(
              //      " value.data,",
              //       token,
              //     ),
              //     success: (value) {
              //       print("======图片压缩成功=======");
              //       process.state = 1;
              //       var type = ConvertType.toLowerCase();
              //       List<String> splitString =
              //           process.name.split("."); // 以逗号和空格为分隔符拆分字符串
              //       String substring = splitString[0];
              //       saveFile(value.data, "$substring.zip").then((v) {
              //         EventBusUtil.fireEvent(
              //             Bus(Constant.CONVERT_MSG, process));
              //         update(id, 1, path: v);
              //         if (type == "pdf") {
              //           EventBusUtil.fireEvent(
              //               Bus(Constant.ADD_FILE_MSG, File(v)));
              //         }
              //       });
              //     });
            } else {
              apiShow(
                  api: convert(file.path, ConvertType, token),
                  success: (value) {
                    process.state = 1;
                    var type = ConvertType.toLowerCase();
                    List<String> splitString =
                        process.name.split("."); // 以逗号和空格为分隔符拆分字符串
                    String substring = splitString[0];
                    saveFile(value.data, "$substring.$type").then((v) {
                      EventBusUtil.fireEvent(
                          Bus(Constant.CONVERT_MSG, process));
                      update(id, 1, path: v);
                      if (type == "pdf") {
                        EventBusUtil.fireEvent(
                            Bus(Constant.ADD_FILE_MSG, File(v)));
                      }
                    });
                  },
                  failure: (e) {
                    process.state = 2;
                    EventBusUtil.fireEvent(Bus(Constant.CONVERT_MSG, process));
                    update(id, 2, error: "convert_fail".tr);
                  });
            }
          },
          failure: (e) {});
    } else {
      // 处理用户取消选择文件的情况
    }
  }

  getType(Types type) {
    List<String> list1 = [
      "TXT",
      "JPEG",
      "PNG",
      "BMP",
      "SVG",
      "TIFF",
      "DOC",
      "DOCX",
      "RTF",
      "DOT",
      "DOTX",
      "DOTM",
      "FlatOPC",
      "EMF",
      "PCL",
      "HTML",
      "MHTML",
      "HtmlFixed",
      "ODT",
      "OTT"
    ];
    List<String> list2 = ["PDF"];

    return type.label == 2 ? list1 : list2;
  }

  Future<int> setData(Process process) async {
    await dbUtil.open();
    Map<String, dynamic> paramters = <String, dynamic>{};
    paramters["name"] = process.name;
    paramters["path"] = process.path;
    paramters["type"] = process.type;
    paramters["img"] = process.img;
    paramters["value"] = process.value;
    paramters["state"] = process.state;
    paramters["error"] = process.error;
    return await dbUtil.insertByHelper(processing, paramters);
  }

  update(int id, int state, {String? error, String? path}) async {
    await dbUtil.open();
    Map<String, Object> paramters = <String, Object>{};
    paramters["state"] = state;

    if (path != null) {
      paramters["path"] = path!;
    }
    if (error != null) {
      paramters["error"] = error!;
    }
    await dbUtil?.updateByHelper(processing, paramters, 'id=?', [id]);
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      body: Column(
        children: [
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: [
                  MyLocalImage(
                    widget.type.img,
                    width: 76,
                    height: 76,
                    onclick: () {},
                  ),
                  TextView(
                    widget.type.name,
                    margin: const EdgeInsets.only(top: 16),
                    style: TextStyle(
                        color: rgba(48, 49, 51, 1),
                        fontSize: 20,
                        fontWeight: FontWeight.bold),
                  ),
                  if (userEntity!.is_vip == "0")
                    TextView(
                      "${"free_usage".tr} ${userEntity!.counts}",
                      margin: const EdgeInsets.only(top: 4),
                      style: TextStyle(
                          color: int.parse(userEntity!.counts.toString()) == 0
                              ? rgba(255, 0, 14, 1)
                              : rgba(100, 101, 102, 1),
                          fontSize: 12),
                    ),
                  if (userEntity?.is_vip == "0")
                    Container(
                      height: 60,
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      margin: const EdgeInsets.symmetric(vertical: 24),
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                            rgba(221, 245, 253, 1),
                            rgba(204, 206, 251, 1),
                          ]),
                          borderRadius: BorderRadius.circular(6)),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const MyLocalImage(
                            Res.banner_icon_crow,
                            width: 32,
                            height: 32,
                          ),
                          Expanded(
                            child: Container(
                              margin: const EdgeInsets.only(left: 12),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  TextView(
                                    "to_pro".tr,
                                    style: TextStyle(
                                        color: ColorUtils.text,
                                        fontSize: 14,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  TextView("unlock_unlimited".tr,
                                      margin: const EdgeInsets.only(top: 4),
                                      style: TextStyle(
                                          color: ColorUtils.text_,
                                          fontSize: 12)),
                                ],
                              ),
                            ),
                          ),
                          MyLocalImage(
                            Res.nav_icon_getpro,
                            width: 75,
                            height: 32,
                            onclick: () {
                              Get.to(const Subscribe());
                            },
                          )
                        ],
                      ),
                    ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 10),
                    child: const Divider(
                      height: 1,
                    ),
                  ),
                  Row(
                    children: [
                      TextView(
                        'feature'.tr,
                        margin: const EdgeInsets.symmetric(vertical: 20),
                        style: TextStyle(color: ColorUtils.text, fontSize: 16),
                      ),
                      const Spacer()
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        width: 4,
                        height: 4,
                        margin: const EdgeInsets.only(top: 7),
                        decoration: BoxDecoration(
                            color: rgba(150, 151, 153, 1),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(2))),
                      ),
                      Expanded(
                        child: TextView(
                          widget.type.label == 2
                              ? "select_a_file".tr
                              : "${"select_pdf".tr}${widget.type.name} ${"format".tr}",
                          maxLines: 2,
                          margin: const EdgeInsets.only(left: 10, right: 30),
                          style: TextStyle(color: ColorUtils.text_),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        width: 4,
                        height: 4,
                        margin: const EdgeInsets.only(top: 7),
                        decoration: BoxDecoration(
                            color: rgba(150, 151, 153, 1),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(2))),
                      ),
                      Expanded(
                        child: TextView(
                          "${"supported".tr} ${widget.type.label != 2 ? widget.type.types.join(', ') : ""}",
                          maxLines: 2,
                          textAlign: TextAlign.start,
                          margin: const EdgeInsets.only(left: 10, right: 10),
                          style: TextStyle(color: ColorUtils.text_),
                        ),
                      ),
                    ],
                  ),
                  Visibility(
                    visible: widget.type.label == 2 ? true : false,
                    child: Container(
                      margin: const EdgeInsets.only(top: 12),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: rgba(247, 247, 247, 1)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                              "Word: DOC, DOCX, RTF, DOT, DOTX, DOTM, FlatOPC (XML)\nOpenOffice: ODT, OTT \nWordprocessingML: XML \nWeb: HTML, MHTML, HtmlFixed \nText: TXT",
                              textAlign: TextAlign.start,
                              style: TextStyle(
                                  color: ColorUtils.text_, height: 1.7)),
                        ],
                      ),
                    ),
                  ),
                  Visibility(
                    visible: widget.type.types.length > 1 ? true : false,
                    child: Container(
                        margin: const EdgeInsets.only(top: 30),
                        alignment: Alignment.centerLeft,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            TextView(
                              "select_conversion".tr,
                              style: TextStyle(
                                  color: ColorUtils.text,
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold),
                            ),
                            InkWell(
                              onTap: () {
                                Get.bottomSheet(TypeDialog(
                                  types: widget.type.types,
                                  setType: setType,
                                ));
                              },
                              child: Container(
                                height: 40,
                                margin: const EdgeInsets.only(top: 20),
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 12),
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(4),
                                    border: Border.all(
                                        color: rgba(200, 202, 204, 1))),
                                child: Row(
                                  children: [
                                    TextView(
                                      ConvertType,
                                      style: TextStyle(color: ColorUtils.text_),
                                    ),
                                    const Spacer(),
                                    const MyLocalImage(
                                      Res.xiala,
                                      width: 14,
                                      height: 14,
                                    )
                                  ],
                                ),
                              ),
                            )
                          ],
                        )),
                  ),
                ],
              ),
            ),
          ),
          const Divider(
            height: 1,
          ),
          userEntity!.is_vip == "0" && userEntity!.counts == "0"
              ? Go()
              : select()
        ],
      ),
    );
  }

  Widget Go() {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6),
          gradient: LinearGradient(
              colors: [rgba(129, 8, 255, 1), rgba(245, 98, 183, 1)])),
      margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
      child: TextView(
        "Get Pro",
        height: 50,
        alignment: Alignment.center,
        style: const TextStyle(
            color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
        onclick: () {
          Get.to(const Subscribe());
        },
      ),
    );
  }

  Widget select() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      alignment: Alignment.center,
      child: MaterialButton(
        onPressed: () {
          checkPermission();
        },
        minWidth: double.infinity,
        color: rgba(255, 78, 77, 1),
        height: 48,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(6),
        ),
        child: TextView(
          "select_file".tr,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}
